<?php defined('SYSPATH') or die('No direct script access.');

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/9/28 15:39
 * Desc: 微信快速登录
 */
class Controller_Pc_Api_V2_Member_WxClient extends Controller_Pc_Api_v2_Base
{
    // 数据请求结果
    private $result;

    /**
     * 参数验证对象
     * @var Request_Api_V2_Member_Wxclient
     */
    private $validation;

    /**
     * 服务
     * @var Service_Api_Member_Wxclient
     */
    private $service;

    public function before()
    {
        parent::before();

        if (!St_Functions::is_normal_app_install('weixinquicklogin')) {
            $this->result['status'] = false;
            $this->result['msg']    = '请安装微信快速登录';
            exit();
            $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
        }

        // 返回数据
        $this->result = array('status' => true, 'msg' => '操作成功', 'data' => array());

        // 验证
        $this->validation = Request_Api_V2_Factory::create('member_wxclient', $this->request_params);

        // 服务
        $this->service = new Service_Api_Member_WxClient();

    }

    public function after()
    {
        $this->send_datagrams($this->client_info['id'], $this->result, $this->client_info['secret_key']);
    }

    // 获取微信快速登录信息
    public function action_login()
    {
        try {
            $this->result['data'] = $this->service->login($this->request_params);
        } catch (Exception $e) {
            $this->result = array('status' => false, 'msg' => $e->getMessage());
        }
    }

    // 微信回调
    public function action_callback()
    {
        $db = Database::instance();
        $db->begin();
        try {
            $this->validation->callback()->check();

            $this->result = $this->service->callback($this->request_params);

            $db->commit();
        } catch (Exception $e) {
            $this->result = array('status' => false, 'msg' => $e->getMessage());

            $db->rollback();
        }
    }
}